<template>
  <div class="appointment-page">
    <van-nav-bar title="预约服务" />

    <van-tabs v-model:active="activeTab" sticky>
      <!-- ==================== 我要预约 Tab ==================== -->
      <van-tab title="我要预约">
        <div class="booking-form-container">
          <van-form @submit="onSubmitBooking">
            <van-cell-group inset title="访客信息">
              <van-field
                v-model="bookingForm.visitorName"
                name="visitorName"
                label="访客姓名"
                placeholder="请输入访客姓名"
                :rules="[{ required: true, message: '请填写姓名' }]"
              />
              <van-field
                v-model="bookingForm.visitorPhone"
                name="visitorPhone"
                label="联系电话"
                placeholder="请输入联系电话"
                type="tel"
                :rules="[{ required: true, message: '请填写电话' }]"
              />
            </van-cell-group>

            <van-cell-group inset title="预约详情">
              <van-field
                v-model="bookingForm.elderlyName"
                label="探访老人"
                readonly
              />
              <van-field
                v-model="formattedDate"
                is-link
                readonly
                name="date"
                label="探访日期"
                placeholder="点击选择日期"
                @click="showCalendar = true"
                :rules="[{ required: true, message: '请选择日期' }]"
              />
              <van-field
                v-model="bookingForm.visitTimeSlot"
                is-link
                readonly
                name="time"
                label="探访时段"
                placeholder="点击选择时段"
                @click="showTimePicker = true"
                :rules="[{ required: true, message: '请选择时段' }]"
              />
            </van-cell-group>

            <div class="submit-button-wrapper">
              <van-button round block type="primary" native-type="submit" :loading="isSubmitting">
                提交预约
              </van-button>
            </div>
          </van-form>
        </div>
      </van-tab>

      <!-- ==================== 我的预约 Tab ==================== -->
      <van-tab title="我的预约">
        <div class="appointment-list-container">
          <van-empty v-if="appointmentList.length === 0" description="暂无预约记录" />
          <div v-else>
            <div v-for="item in appointmentList" :key="item.id" class="appointment-card">
              <div class="card-header">
                <span class="visitor-name">访客: {{ item.visitorName }}</span>
                <van-tag :type="statusInfo[item.status].type">{{ statusInfo[item.status].text }}</van-tag>
              </div>
              <div class="card-body">
                <p><van-icon name="friends-o" /> 探访老人: {{ item.elderlyName }}</p>
                <p><van-icon name="clock-o" /> 预约时间: {{ item.visitTime }}</p>
              </div>
              <div class="card-footer" v-if="item.status === 'pending'">
                <van-button size="small" round @click="cancelPending(item.id)">取消预约</van-button>
              </div>
              <div class="card-footer" v-if="item.status === 'approved'">
                <van-button size="small" round @click="submitCancelApproved(item.id)">取消预约</van-button>
              </div>
            </div>
          </div>
        </div>
      </van-tab>
    </van-tabs>

    <!-- 日期选择弹出层 -->
    <van-calendar v-model:show="showCalendar" @confirm="onDateConfirm" :min-date="minDate" />

    <!-- 时间选择弹出层 -->
    <van-action-sheet
      v-model:show="showTimePicker"
      :actions="availableTimeSlots"
      cancel-text="取消"
      close-on-click-action
      @select="onTimeSelect"
      title="请选择探访时段"
    />
  </div>
</template>


<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { showToast, showConfirmDialog } from 'vant';
import 'vant/es/dialog/style';
import {
  submitLeaveRequest,
  cancelPendingLeaveRequest,
  submitCancelApprovedLeaveRequest,
  listLeaveRequests
} from '../../api/LeaveRequest.js';

// --- 状态管理 ---
const activeTab = ref(0);
const isSubmitting = ref(false);

// --- 我要预约 Tab ---
const bookingForm = ref({
  visitorName: '王女士', // 可从登录用户信息获取
  visitorPhone: '13812345678', // 可从登录用户信息获取
  elderlyName: '李秀英', // 被探访的老人姓名
  visitDate: '',
  visitTimeSlot: '',
});

// 提交表单相关
const leaveRequestDTO = ref({
  elderlyUserId: 1,
  reasonType: 'family_reunion',
  reasonDetails: '',
  startTime: null,
  endTime: null
});

const showCalendar = ref(false);
const showTimePicker = ref(false);
const minDate = new Date(); // 只能预约今天及之后的日期

// 可选的探访时间段
const availableTimeSlots = [
  { name: '09:00 - 10:00' },
  { name: '10:00 - 11:00' },
  { name: '14:00 - 15:00' },
  { name: '15:00 - 16:00' },
];

// 状态映射，用于显示文本和标签颜色
const statusInfo = {
  pending: { text: '待审核', type: 'warning' },
  approved: { text: '已通过', type: 'success' },
  rejected: { text: '已拒绝', type: 'danger' },
  finished: { text: '已完成', type: 'default' },
  cancelled: { text: '已取消', type: 'default' },
  on_leave: { text: '待取消', type: 'warning' },
};

// 格式化日期时间函数
const formatDateTime = (date, time) => {
  const [year, month, day] = date.split('-');
  const [start, end] = time.split(' - ');
  const startTime = `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')} ${start}`;
  const endTime = `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')} ${end}`;
  return { startTime, endTime };
};

const formattedDate = computed(() => {
  if (!bookingForm.value.visitDate) return '';
  const date = new Date(bookingForm.value.visitDate);
  return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
});

const onDateConfirm = (date) => {
  bookingForm.value.visitDate = date;
  showCalendar.value = false;
};

const onTimeSelect = (item) => {
  bookingForm.value.visitTimeSlot = item.name;
  showTimePicker.value = false;
};

const onSubmitBooking = async () => {
  isSubmitting.value = true;
  // 修改此处，直接使用 showToast 并传入配置对象
  showToast({
    message: '正在提交...',
    forbidClick: true,
    duration: 1500,
    type: 'loading' // 添加 type 为 loading
  });

  // 设置访客信息到 reasonDetails
  leaveRequestDTO.value.reasonDetails = `【${bookingForm.value.visitorName}】`;

  // 转换探访日期和探访时段为 startTime 和 endTime
  const { startTime, endTime } = formatDateTime(formattedDate.value, bookingForm.value.visitTimeSlot);
  leaveRequestDTO.value.startTime = startTime;
  leaveRequestDTO.value.endTime = endTime;

  try {
    const response = await submitLeaveRequest(leaveRequestDTO.value);
  
    showToast({ type: 'success', message: '预约提交成功, 请等待审核' });
    // 重置表单
    bookingForm.value = {
      visitorName: '',
      visitorPhone: '',
      elderlyName: '李秀英',
      visitDate: '',
      visitTimeSlot: ''
    };
    leaveRequestDTO.value = {
      elderlyUserId: 1,
      reasonType: 'family_reunion',
      reasonDetails: '',
      startTime: null,
      endTime: null
    };
    // 刷新预约列表
    getLeaveRequests();
 
  } catch (error) {
    showToast({ type: 'fail', message: '申请提交失败，请稍后重试' });
  } finally {
    isSubmitting.value = false;
  }
};

// --- 我的预约 Tab ---
const appointmentList = ref([]);

/**
 * 获取请假记录
 */
const getLeaveRequests = async () => {
  try {
    const queryDTO = {
      elderlyUserId: 1,
      reasonType: 'family_reunion',
      reasonDetails: '',
      startTime: null,
      endTime: null
    };
    const response = await listLeaveRequests(queryDTO);

    // 增强响应格式检查
    appointmentList.value = response.list.map(item => {
      const visitorName = item.reasonDetails.replace(/【|】/g, '');
      const startTimeStr = item.startTime.split(' ')[0];
      const start = item.startTime.split(' ')[1];
      const end = item.endTime.split(' ')[1];
      const visitTime = `${startTimeStr} ${start} - ${end}`;
      return {
        ...item,
        visitorName,
        elderlyName: '李秀英',
        visitTime
      };
    });
    
  } catch (error) {
    console.error('请求异常:', error);
    showToast({ type: 'fail', message: '网络异常，请稍后重试' });
  }
};

/**
 * 取消待审核申请
 */
const cancelPending = async (id) => {
  try {
    await cancelPendingLeaveRequest(id);
    showToast({ type: 'success', message: '取消成功' });
    // 重新加载数据
    getLeaveRequests();
  } catch (error) {
    console.error('取消失败:', error);
    showToast({ type: 'fail', message: '取消失败，请重试' });
  }
};

/**
 * 提交已批准申请的取消
 */
const submitCancelApproved = async (id) => {
  try {
    await submitCancelApprovedLeaveRequest(id);
    showToast({ type: 'success', message: '已提交取消申请，等待审核' });
    // 重新加载数据
    getLeaveRequests();
  } catch (error) {
    console.error('提交取消失败:', error);
    showToast({ type: 'fail', message: '提交取消失败，请重试' });
  }
};

// 页面加载时获取数据
onMounted(() => {
  getLeaveRequests();
});
</script>

<style scoped>
.appointment-page {
  background-color: #f7f8fa;
  min-height: 100vh;
}
.booking-form-container {
  padding: 16px 0;
}
.submit-button-wrapper {
  margin: 24px 16px;
}

.appointment-list-container {
  padding: 16px;
}
.appointment-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebedf0;
}
.visitor-name {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
}
.card-body {
  padding: 12px 0;
  font-size: 14px;
  color: #646566;
}
.card-body p {
  margin: 8px 0;
  display: flex;
  align-items: center;
}
.card-body .van-icon {
  margin-right: 8px;
  color: #969799;
}
.card-footer {
  text-align: right;
  padding-top: 12px;
  border-top: 1px solid #ebedf0;
}
</style>